export default {
	// 为当前模块开启命名空间
	namespaced: true,
	state: {
		cartList: JSON.parse(uni.getStorageSync('cartList') || '[]')
	},
	mutations: {
		addGoods(state, play) {
			const findResult = state.cartList.find((x) => {
				return x.goods_id === play.goods_id
			})

			if (!findResult) {
				state.cartList.push(play)
			} else {
				findResult.goods_count++
			}

			uni.setStorageSync('cartList', JSON.stringify(state.cartList))
		},
		// 更新购物列表单选框
		updateGoodsRadio(state, paly) {
			const findResult = state.cartList.find(item => {
				return item.goods_id === paly.goods_id
			})

			if (findResult) {
				findResult.goods_state = paly.goods_state

				uni.setStorageSync('cartList', JSON.stringify(state.cartList))
			}

		},
		// 更新购物列表numberBox
		updateNumberBox(state, play) {
			const findResult = state.cartList.find((item) => {
				return item.goods_id === play.goods_id
			})

			if (findResult) {
				findResult.goods_count = play.goods_count

				uni.setStorageSync('cartList', JSON.stringify(state.cartList))
			}
		},
		// 根据 Id 从购物车中删除对应的商品信息
		removeGoodsById(state, goods_id) {
			// 调用数组的 filter 方法进行过滤
			state.cartList = state.cartList.filter(x => x.goods_id !== goods_id.goods_id)
			// 持久化存储到本地
			uni.setStorageSync('cartList', JSON.stringify(state.cartList))
		},
		// 反选状态
		updateAllGoodsState(state, newState) {
			 state.cartList.forEach(x => x.goods_state = newState)
			 // 持久化存储到本地
			 uni.setStorageSync('cartList', JSON.stringify(state.cartList))
		}
	},
	getters: {
		cartTotal(state) {
			let t = 0;
			state.cartList.forEach((x) => t += x.goods_count)
			return t
		},
		// 全选状态
		// 购物车是否是全选
		goodsTotal(state) {
			return state.cartList.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count, 0)
		},
		// 计算勾选商品价格
		checkTotal(state) {
			return state.cartList.filter(x => x.goods_state).reduce((total, item) => total += item.goods_price, 0).toFixed(2)
		}
	}
}
